import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_my_web/pages/tools/drop_draw_board/base/build_utils.dart';
import 'package:flutter_my_web/pages/tools/drop_draw_board/base/base_drop_widget.dart';
import 'package:flutter_my_web/pages/tools/drop_draw_board/event/bulid_draw_board_json_event.dart';
import 'package:flutter_my_web/pages/tools/drop_draw_board/event/refresh_draw_board_event.dart';
import 'package:flutter_my_web/pages/tools/drop_draw_board/showbuildwidget/show_build_widget.dart';
import 'package:flutter_my_web/utils/Utils.dart';
import 'package:get/get.dart';

//画板
//1.如何删除控件，通过侧边版删除
//控件如何交换位置
class DrawBoardWidget extends StatefulWidget {
  const DrawBoardWidget({Key? key}) : super(key: key);

  @override
  State<DrawBoardWidget> createState() => _DrawBoardWidgetState();
}

int setId = 0;

class _DrawBoardWidgetState extends State<DrawBoardWidget> {
  List<BaseDropWidget> values = [];
  StreamSubscription? refreshDrawBoardEventListen;
  StreamSubscription? buildDrawBoardJsonEventBusListen;
  @override
  void initState() {
    super.initState();
    refreshDrawBoardEventListen = refreshDrawBoardEvent.on().listen((event) {
      // print("收到");
      setState(() {

      });
    });
    buildDrawBoardJsonEventBusListen = buildDrawBoardJsonEventBus.on().listen((event) {
      var list = [];
      values.forEach((element) {
        list.add(element.dropBean.toJson());
      });
      print(jsonEncode(list));
      Get.to(ShowBuildWidget(jsonEncode(list)));
    });
  }

  @override
  void dispose() {
    super.dispose();
    refreshDrawBoardEventListen?.cancel();
    buildDrawBoardJsonEventBusListen?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: DragTarget<BaseDropWidget>(
        onMove: (tag) { //移动过程中
          print(tag.offset.toString());
        },
        onWillAccept: (e) {
          return true;
        },
        onAccept: (o) {
          if (o.dropBean.drawBoardId > 0) {
            print("widget.dropBean.drawBoardId:${o.dropBean.drawBoardId}");
            values.remove(o);
            values.add(o);
            return;
          }
          var widget = buildBaseDropWidgetByType(o.dropBean);
          if (widget == null) {
            showSnackBar("添加错误");
            return;
          }
          widget.dropBean.drawBoardId = ++setId;
          values.add(widget);
          setState(() {});
        },
        builder: (BuildContext context, List<Object?> candidateData,
            List<dynamic> rejectedData) {
          return SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Container(
              color: Colors.grey[200],
              width: 375,
              height: 900,
              child: SingleChildScrollView(
                child: Column(children: values,),
              ),
            ),
          );
        },
      ),
    );
  }
}
